package com.example.javafx.bilibilidownload.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class OpetateFileUtil {


    private static final Logger log = LogManager.getLogger(OpetateFileUtil.class);

    // 成功标志，0成功，-1失败
    private int result = 0;
    //文件总数
    private static float count = 0;

    /**
     * @Description:删除目录下所有文件，并删除目录，传入目录地址
     * @Param: [path]
     * @return: int
     * @Author: Mr.zengbang
     * @Date: 2020/5/11
     */
    public int deleteAllFileInPath(String path) throws IOException {

        if (!Files.exists(Paths.get(path))) {
            return result;
        }
        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                log.info("pre visit dir:" + file);
                Files.deleteIfExists(file);
                log.info("delete file success:" + file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                log.error("visit file failed: " + file);
                result = -1;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                System.out.println("post visit directory: " + dir);
                Files.delete(dir);
                log.info("delete dir success:" + dir);
                return FileVisitResult.CONTINUE;
            }
        });
        return result;
    }

    /**
     * @Description:传入路径，得到路径下所有的文件数量
     * @Param: [path]
     * @return: float
     * @Author: Mr.zengbang
     * @Date: 2020/6/22
     */
    public static float getFileNum(String path) throws IOException {

        count = 0F;
        if (!Files.exists(Paths.get(path))) {
            return 0F;
        }
        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                count++;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
        return count;
    }

    /**
     * @Description:得到路径下所有的文件路径集合
     * @Param: [path]
     * @return: java.util.List<java.lang.String>
     * @Author: Mr.zengbang
     * @Date: 2020/12/14
     */
    public static List<String> getFileNameList(String path) throws IOException {


        List<String> fileStringList = new ArrayList<>();
        if (!Files.exists(Paths.get(path))) {
            return fileStringList;
        }
        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                fileStringList.add(file.getFileName().toString());
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
        return fileStringList;
    }


    /**
     * @Description:检查源文件是否存在，目标文件目录是否创建好
     * @Param: [originFilePath, targetFilePath]
     * @return: void
     * @Author: Mr.zengbang
     * @Date: 2020/6/23
     */
    public static void checkOriginAndTarget(String originFilePath, String targetFilePath) {
        checkOrigin(originFilePath);
        checkTarget(targetFilePath);
    }

    /**
     * @Description:检查源文件是否存在
     * @Param: [originFilePath]
     * @return: void
     * @Author: Mr.zengbang
     * @Date: 2020/6/23
     */
    public static void checkOrigin(String originFilePath) {

        if (Files.notExists(Paths.get(originFilePath))) {
            log.error("!!!!!!!!!!!源文件不存在!{}", originFilePath);
            throw new RuntimeException("!!!!!!!!!!!源文件不存在!" + originFilePath);
        }
    }

    /**
     * @Description:检查目标文件父目录情况
     * @Param: [targetFilePath]
     * @return: void
     * @Author: Mr.zengbang
     * @Date: 2020/6/23
     */
    public static void checkTarget(String targetFilePath) {

        targetFilePath = targetFilePath.replace(" ", "").trim();
        try {
            Files.createDirectories(Paths.get(targetFilePath).getParent());
        } catch (Exception e) {
            log.error("!!!!!!!!!!!创建目标文件目录失败{}", targetFilePath);
            throw new RuntimeException("!!!!!!!!!!!创建目标文件目录失败!" + targetFilePath + e.getMessage());
        }
    }

    public static String getType(String filePath) {
        return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
    }
}
